# 内部tcp，数据服务与我们自己的图文系统连接

_plugin_name = "TCPMgr"
_plugin_version = "1.0.0"

import socket
import threading
import signal
import time
import errno

tcpRun = False

def receive_data(conn):
    global tcpRun
    count = 10
    while tcpRun:
        # 接收包长信息
        try:
            lengthBytes = conn.recv(4)
            dataLength = int.from_bytes(lengthBytes, byteorder='little')
            data = b''
            while len(data) < dataLength:
                packet = conn.recv(dataLength - len(data))
                if not packet: break
                data += packet
            print("Received:", data.decode())
            if count >0:
                send("python send ")
                count -= 1
            # # 在这里处理接收到的数据
            # try:
            #     if not isNullOrEmpty(data.decode()):
            #         send("python send")
            # except Exception as e:
            #     print(e)
        except socket.error as e:
            if e.errno == errno.WSAEWOULDBLOCK:
                time.sleep(0.1)
                continue

receive_thread = None

def signal_handler(sig,frame):
    global tcpRun
    tcpRun = False

def isNullOrEmpty(s):
    return s is None or len(s)==0

def send(msg):
    global client
    print("fa")
    if client is not None:
        dataLength = len(msg)
        # 发送包长信息
        lengthBytes = dataLength.to_bytes(4, byteorder='little')

        client.sendall(lengthBytes)
        # 发送数据
        client.sendall(msg.encode())


def run():
    # 创建TCP连接
    TCP_IP = "127.0.0.1"
    TCP_PORT = 55555

    global receive_thread
    global tcpRun
    global client
    # 设置接收系统中断
    # signal.signal(signal.SIGINT, signal_handler)
    # 连接
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        tcpRun = True
        client.connect((TCP_IP, TCP_PORT))
        client.setblocking(False)  # 非阻塞
        # 创建接收消息的线程
        receive_thread = threading.Thread(target=receive_data, args=(client,))
        receive_thread.start()
        print("connect ok ")
    except Exception as e:
        tcpRun = False
        print(f"connect error {e}")

def stop():
    global tcpRun
    tcpRun = False
    # 主线程可以继续执行其他任务
    # 例如，可以在主线程中发送消息

    # 关闭连接
    # client.close()

